﻿using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using GameObjects;
using GameObjects.DrawableClasses;
using GameProcess;
using Microsoft.Xna.Framework;
using Network;
using Virvar.Net;

namespace StillAlive
{
    class Communicator
    {
        public string ServerAddress = null;
        public int ServerConnectionPort = -1;
        public int ServerPort = -1;
        public int ClientPort = 7778;
        private int receiveTimeout = 5000;

        private IMessager _messager; // для входящих сообщений
        private int updateRate = 40; // период между обновлениями
        private bool shouldContinue = true; // для завершения потока
        Vector2 previosPos;

        public Communicator(out RealCharacter player)
        {
            using (StreamReader sr = new StreamReader("Settings.txt"))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    if (line.StartsWith("[Server]"))
                    {
                        ServerAddress = line.Split('"')[1];
                    }
                    else if (line.StartsWith("[ServerPort]"))
                    {
                        ServerPort = int.Parse(line.Split('"')[1]);
                    }
                    else if (line.StartsWith("[ServerConnectionPort]"))
                    {
                        ServerConnectionPort = int.Parse(line.Split('"')[1]);
                    }
                }
            }
            if (ServerAddress == null || ServerConnectionPort == -1 || ServerPort == -1)
                throw new Exception("В Settings.txt отсутствуют все необходимые данные о сервере.");
            // подключаемся к серверу
            ServerConnectionPacket connMsg = Connect(ref ClientPort);
            if (connMsg == null)
                Battlefield.Instance.Game.Exit();
            _messager = new UdpMessager(ServerAddress, ServerPort, ClientPort, receiveTimeout);
            GameState.Instance.SetLevel((Level)connMsg.Level);
            // обновление состояния игрока
            GameState.Instance.CreateCharacter(connMsg.PlayerId);
            player = GameState.Instance.Players[connMsg.PlayerId];
            player.Position = (Vector2)connMsg.PlayerPosition;
            player.Health = connMsg.Health;
            player.Speed = connMsg.Speed;
            //GameState.Instance.SetLevel((Level)connMsg.Level);
            player.MoveBehavior = new PlayerMove1(player);
            previosPos = player.Position;
            GameState.Instance.Player = player;

            GameState.Instance.NetPlayer = new NetPlayer(_messager, player);
            // начинаем принимать сообщения
            new Thread(StartReceiving).Start();
            // начинаем отправлять сообщения
            new Thread(Send).Start();
        }

        ServerConnectionPacket Connect(ref int port)
        {
            // подключаемся к серверу
            ServerConnectionPacket connAnswer = null;
            ProtoMessager<ConnectionMessage> connMessager = null;
            for (int j = 0; j < 20; j++)
            {
                try
                {
                    connMessager = new ProtoMessager<ConnectionMessage>(new UdpMessager(ServerAddress, ServerConnectionPort, port));
                    break;
                }
                catch
                {
                    port++;
                }
            }
            if (connMessager == null)
            {
                Trace.WriteLine("Failed to connect.");
            }
            else
            {
                ConnectionMessage connMsg = new ConnectionMessage(port);
                for (int i = 0; i < 10; i++)
                {
                    connMessager.Send(connMsg);
                    try
                    {
                        connAnswer = (ServerConnectionPacket)connMessager.Receive<ServerConnectionPacket>();
                        break;
                    }
                    catch
                    {
                        // временно
                        Battlefield.Instance.PacketLength = -1;
                    }
                }
                connMessager.Close();
                if (connAnswer != null)
                {
                    Trace.WriteLine("Connection succesful.");
                }
                else
                {
                    Trace.WriteLine("Failed to connect.");
                }
            }
            // возвращаем ответ от сервера
            return connAnswer;
        }

        void StartReceiving()
        {
            // запускаем поток получения сообщений от клиентов
            while (shouldContinue)
            {
                Receive();
            }
        }

        public void Stop()
        {
            shouldContinue = false;
            Battlefield.Instance.PacketLength = 0;
            GameState.Instance.Stop();
            _messager.Close();
        }

        // добавляем нового игрока в игру
        //void AddPlayer(PlayerInfo playerState)
        //{
        //    Battlefield.Instance.CreateCharacter(playerState);
        //}

        // удаление игрока, вышедшего из игры
        void RemovePlayer(byte playerId)
        {
            Battlefield.Instance.RemoveCharacter(playerId);
        }

        // отправка данных
        void Send(object state)
        {
            // начинаем отправлять сообщения
            while (shouldContinue)
            {
                GameState.Instance.Send();
                Thread.Sleep(updateRate);
            }
        }

        // получение данных
        void Receive()
        {
            byte[] data = _messager.Receive();
            ServerPacket packet = (ServerPacket)GameState.Instance.Parse(data);
            if (data == null)
            {
                return;
            }
            Battlefield.Instance.PacketLength = data.Length;
        }
    }
}
